#include "RenderToTexture.h"

RenderToTexture::RenderToTexture(int scaleDown)
{
	//generate buffers
	glGenRenderbuffers(1, &m_depthBuffer);
	glGenFramebuffers(1, &m_frameBuffer);
	glGenTextures(1, &m_texture);	

	//create texture
	glBindTexture(GL_TEXTURE_2D, m_texture);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, screenWidth/scaleDown, screenHeight/scaleDown, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

	//create depth buffer
	glBindRenderbuffer(GL_RENDERBUFFER, m_depthBuffer);	
	glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, screenWidth/scaleDown, screenHeight/scaleDown);

	//attach to our framebuffer
	glBindFramebuffer(GL_FRAMEBUFFER, m_frameBuffer);
	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthBuffer);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_texture, 0);

	glBindFramebuffer(GL_FRAMEBUFFER, 0);

	w = screenWidth/scaleDown;
	h = screenHeight/scaleDown;
}
RenderToTexture::~RenderToTexture()
{
	glDeleteFramebuffers(1, &m_frameBuffer);
	glDeleteRenderbuffers(1, &m_depthBuffer);
	glDeleteTextures(1, &m_texture);
}
void RenderToTexture::begin()
{
	glBindFramebuffer(GL_FRAMEBUFFER, m_frameBuffer);
	glViewport(0, 0, w, h);
	active = true;
}
void RenderToTexture::end()
{
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glViewport(0, 0, screenWidth, screenHeight);
	active = false;
}
